package com.beaven.imclient.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.beaven.imclient.R;
import com.beaven.model.model.card.UserCard;
import java.util.List;

/**
 * author: Beaven
 * time: 2017/5/26 10:56
 *
 * 好友搜索Adapter
 */

public class UserSearchAdapter extends RecyclerView.Adapter<UserSearchAdapter.UserSearchHolder> {

  private List<UserCard> userCardList;
  private OnAddUserListener listener;

  public UserSearchAdapter(List<UserCard> userCardList) {
    this.userCardList = userCardList;
  }

  public void setListener(OnAddUserListener listener) {
    this.listener = listener;
  }

  public void addUserList(List<UserCard> userCards) {
    if (userCards != null && userCards.size() > 0) {
      int start = userCardList.size();
      userCardList.addAll(userCards);
      notifyItemRangeInserted(start, userCardList.size());
    }
  }

  public void clearList() {
    userCardList.clear();
    notifyDataSetChanged();
  }

  public void setUserCard(int position, UserCard userCard) {
    userCardList.set(position, userCard);
    notifyItemChanged(position);
  }

  @Override public UserSearchHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view =
        LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_search, parent, false);
    return new UserSearchHolder(view);
  }

  @Override public void onBindViewHolder(final UserSearchHolder holder, int position) {
    final UserCard userCard = userCardList.get(position);
    holder.text_user_name.setText(userCard.getName());
    if (userCard.isFollow()) {
      holder.text_user_add.setVisibility(View.GONE);
    }
    holder.text_user_add.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (listener != null) {
          listener.addUser(userCard);
        }
      }
    });
  }

  @Override public int getItemCount() {
    return userCardList == null ? 0 : userCardList.size();
  }

  public static class UserSearchHolder extends RecyclerView.ViewHolder {

    private TextView text_user_name;
    private TextView text_user_add;

    public UserSearchHolder(View itemView) {
      super(itemView);
      text_user_name = (TextView) itemView.findViewById(R.id.text_user_name);
      text_user_add = (TextView) itemView.findViewById(R.id.text_user_add);
    }
  }

  public interface OnAddUserListener {
    void addUser(UserCard userCard);
  }
}
